//
//  ZWLGameVcViewModel.swift
//  ZWLDY
//
//  Created by czh on 2016/10/9.
//  Copyright © 2016年 zwl. All rights reserved.
//

import UIKit

class ZWLGameVcViewModel: NSObject {
    
    lazy var games : [AnchorGroup] = [AnchorGroup]()

}

extension ZWLGameVcViewModel {
    func loadAllGameData(finishCallBack:@escaping () -> ()) {
        ZWLNetworkTool.sharedTools.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getColumnDetail", parameters: ["shortName" : "game"], successCallBack: { (resultData) -> (Void) in
            
            // 把二进制数据转换成 json 字符串
            guard let jsonStr = String(data: (resultData as? Data)!, encoding: .utf8) else { return }
            
            // 把 json 字符串转换成字典
            guard let resultDict = self.jsonToDict(text: jsonStr) else {return}
            
            guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
            
            // 2.字典转模型
            for dict in dataArray {
                self.games.append(AnchorGroup(dict: dict))
            }
            
            
            finishCallBack()
            
            }) { (error) -> (Void) in
                print(error)
        }
    }
    
    
    
    // MARK:- 把一个格式化好的 json 字符串转换成字典
     func jsonToDict(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
}
